import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/check/click_event.dart';
import 'package:zhibao_flutter/util/config/app_config.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/func/sp_util.dart';
import 'package:zhibao_flutter/zone.dart';

typedef ClickEventCallback = Future<void> Function();

class SwImageData {
  static String swImageDataKey = "swImageDataKey";
  static Timer? timer;

  // static DefaultCacheManager defCache = DefaultCacheManager();

  static List<String> loadedImageData = [];

  static void initData() {
    final spData = SpUtil().get(swImageDataKey);
    if (spData == null) {
      return;
    }
    loadedImageData = List.from(spData);
    LogUtil.d("SwImageData::initData::${loadedImageData.length}");
  }

  static void insertData(String value) {
    if (!strNoEmpty(value)) {
      return;
    }
    if (!value.startsWith("http")) {
      return;
    }
    if (loadedImageData.contains(value)) {
      return;
    }

    timerCancel();

    loadedImageData.add(value);
    timer = Timer.periodic(Duration(seconds: 3), (timer) async {
      await SpUtil().setStringList(swImageDataKey, loadedImageData);
      LogUtil.d(
          "SwImageData::local::success::length::${loadedImageData.length}");
      timerCancel();
    });
  }

  static void timerCancel() {
    timer?.cancel();
    timer = null;
  }

  static Future cacheImgDataOfNetWork(context) async {
    LogUtil.d("SwImageData::cacheImgDataOfNetWork::Start");
    // try {
    //   for (String url in SwImageData.loadedImageData) {
    //     // precacheImage(
    //     //     CachedNetworkImageProvider(url, cacheManager: defCache), context);
    //     await precacheImage(
    //         CachedNetworkImageProvider(
    //           url,
    //           // enableInMemory: true,
    //           // enableCache: true,
    //         ),
    //         context);
    //     // LogUtil.d("SwImageData::cacheImgDataOfNetWork::Render::$url");
    //   }
    // } on FileSystemException catch (e) {
    //   print("cacheImgDataOfNetWork::FileSystemException::${e.toString()}");
    // } catch (e) {
    //   print("cacheImgDataOfNetWork::Error::${e.toString()}");
    // }
    LogUtil.d("SwImageData::cacheImgDataOfNetWork::End");
  }
}

class SwImage extends StatefulWidget {
  final String? image;
  final double? width;
  final double? height;
  final Color? color;
  final BoxFit? fit;
  final String? package;
  final BorderRadius? borderRadius;
  final ClickEventCallback? onTap;
  final EdgeInsetsGeometry? margin;

  final PlaceholderWidgetBuilder? placeholder;

  final LoadingErrorWidgetBuilder? errorWidget;
  final Alignment alignment;

  // Only network image working.
  final bool addOssParam;

  const SwImage(
    this.image, {
    this.width,
    this.height,
    this.color,
    this.fit,
    this.package,
    this.borderRadius,
    this.onTap,
    this.margin,
    this.placeholder,
    this.errorWidget,
    this.alignment = Alignment.center,
    this.addOssParam = true,
    Key? key,
  }) : super(key: key);

  @override
  State<SwImage> createState() => _SwImageState();
}

class _SwImageState extends State<SwImage> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    Widget imageWidget;
    try {
      if (!strNoEmpty(widget.image)) {
        imageWidget = DefImageView(
          width: widget.width,
          height: widget.height,
        );
      } else if (isNetWorkImg(widget.image!)) {
        imageWidget = CachedNetworkImage(
          width: widget.width,
          height: widget.height,

          /// 导致图片模糊，一定要去掉
          // maxHeightDiskCache:
          //     widget.height != null ? ((widget.height! - 45)).round() : null,
          // maxWidthDiskCache:
          //     widget.width != null ? (widget.width)!.round() : null,
          fit: widget.fit,
          color: widget.color,
          alignment: widget.alignment,
          imageUrl: () {
            if (!widget.addOssParam) {
              LogUtil.d("CachedNetworkImage::resultUrl::${widget.image}");
              return widget.image!;
            }
            String resultUrl = widget.image!;
            String startWithOfOss = "?x-oss-process";
            if (resultUrl.contains(startWithOfOss)) return resultUrl;
            if (widget.width != null) {
              final int widthResult =
                  (widget.width! * FrameSize.pixelRatio()).toInt();
              resultUrl = resultUrl +
                  "$startWithOfOss=image/resize,m_mfit,w_$widthResult,h_${widget.height == null ? widthResult : (widget.height! * FrameSize.pixelRatio()).toInt()}";
            }
            // LogUtil.d("CachedNetworkImage:: Real Use resultUrl $resultUrl");
            SwImageData.insertData(resultUrl);
            return resultUrl;
          }(),
          errorWidget: (
            BuildContext context,
            String url,
            dynamic error,
          ) {
            if (widget.errorWidget != null) {
              return widget.errorWidget!(context, url, error);
            } else {
              return Container();
            }
          },
        );
        // imageWidget = CachedNetworkImage(
        //   imageUrl: () {
        //     String resultUrl = widget.image!;
        //     String startWithOfOss = "?x-oss-process";
        //     if (resultUrl.contains(startWithOfOss)) return resultUrl;
        //     if (widget.width != null) {
        //       resultUrl = resultUrl +
        //           "$startWithOfOss=image/resize,m_mfit,w_${widget.width!.toInt()},h_${widget.height == null ? widget.width!.toInt() : widget.height!.toInt()}";
        //     }
        //     LogUtil.d("CachedNetworkImage:: Real Use resultUrl $resultUrl");
        //     SwImageData.insertData(resultUrl);
        //     return resultUrl;
        //   }(),
        //   width: widget.width,
        //   height: widget.height,
        //   fit: widget.fit,
        //   color: widget.color,
        //   alignment: widget.alignment,
        //   cacheManager: SwImageData.defCache,
        //   placeholder: widget.placeholder ??
        //       (context, url) {
        //         return DefImageView(
        //           width: widget.width,
        //           height: widget.height,
        //         );
        //       },
        //   errorWidget: widget.errorWidget ??
        //       (context, url, error) {
        //         return DefImageView(
        //           width: widget.width,
        //           height: widget.height,
        //         );
        //       },
        // );
      } else if (isAssetsImg(widget.image!)) {
        imageWidget = Image.asset(
          widget.image!,
          width: widget.width,
          height: widget.height,
          fit: widget.fit,
          package: widget.package,
          color: widget.color,
          alignment: widget.alignment,
        );
      } else if (File(widget.image!).existsSync()) {
        imageWidget = Image.file(
          File(widget.image!),
          width: widget.width,
          height: widget.height,
          fit: widget.fit,
          color: widget.color,
          alignment: widget.alignment,
        );
      } else if (!strNoEmpty(widget.image)) {
        imageWidget = DefImageView(
          width: widget.width,
          height: widget.height,
        );
      } else {
        try {
          imageWidget = Image.memory(
            widget.image!.codeUnits as Uint8List,
            width: widget.width,
            height: widget.height,
            fit: widget.fit,
            color: widget.color,
            alignment: widget.alignment,
          );
        } catch (e) {
          imageWidget = Image.memory(
            base64Decode(widget.image!),
            width: widget.width,
            height: widget.height,
            fit: widget.fit,
            color: widget.color,
            alignment: widget.alignment,
          );
        }
      }
    } catch (e) {
      LogUtil.d("加载图片出错：${widget.image.toString()}");
      imageWidget = DefImageView(
        width: widget.width,
        height: widget.height,
      );
    }
    if (widget.borderRadius != null) {
      imageWidget = ClipRRect(
          borderRadius: widget.borderRadius ?? BorderRadius.zero,
          child: imageWidget);
    }
    if (widget.onTap != null) {
      imageWidget = InkwellWithOutColor(
        onTap: widget.onTap,
        child: imageWidget,
      );
    }
    if (widget.margin != null) {
      imageWidget = Container(margin: widget.margin, child: imageWidget);
    }

    return imageWidget;
  }

  @override
  bool get wantKeepAlive => true;
}

ImageProvider getDefIcon() {
  return AssetImage('assets/images/pic_register_def_n.png');
}

ImageProvider swImageProvider(String? image) {
  ImageProvider imageProvider;

  if (!strNoEmpty(image)) {
    imageProvider = getDefIcon();
  } else if (image!.startsWith("file://")) {
    imageProvider = FileImage(File(image.replaceAll("file://", "")));
  } else if (isNetWorkImg(image)) {
    imageProvider = CachedNetworkImageProvider(
      image,
      // enableInMemory: true,
      // enableCache: true,
    );
  } else if (isAssetsImg(image)) {
    imageProvider = AssetImage(image);
  } else if (File(image).existsSync()) {
    imageProvider = FileImage(File(image));
  } else {
    imageProvider = MemoryImage(image.codeUnits as Uint8List);
  }
  return imageProvider;
}

/// 同步改一下[11.6]
class DefImageView extends StatelessWidget {
  final double? width;
  final double? height;

  const DefImageView({this.width, this.height});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      decoration: const BoxDecoration(
        color: Color(0xffe1dfe1),
        borderRadius: BorderRadius.all(Radius.circular(5)),
      ),
      child: Image.asset(AppConfig.defPic),
    );
  }
}
